package code

import (
	"fmt"
	"sync"
	"time"
)

var (
	x      int64
	wg     sync.WaitGroup
	lock   sync.Mutex
	rwLock sync.RWMutex
)

func lockSum() {
	for i := 0; i < 1000; i++ {
		lock.Lock()
		x += 1
		lock.Unlock()
	}
	wg.Done()
}

func Concurrence7() {
	wg.Add(2)
	go lockSum()
	go lockSum()
	wg.Wait()
	fmt.Println(x)
}

// 读写锁

func write() {
	// lock.Lock()
	rwLock.Lock()
	x += 1
	time.Sleep(time.Millisecond * 10)
	// lock.Unlock()
	rwLock.Unlock()
	wg.Done()
}

func read() {
	// lock.Lock()
	rwLock.RLock()
	time.Sleep(time.Millisecond * 10)
	// lock.Unlock()
	rwLock.RUnlock()
	wg.Done()
}

func Concurrence8() {
	start := time.Now()
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go write()
	}
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go read()
	}
	wg.Wait()
	end := time.Now()
	fmt.Println(end.Sub(start))
}
